package com.self.listener;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-05-28 13:25
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class MyRegisterService implements RegisterService {

    private final ConcurrentMap<String, Set<NotifyListener>> subscribed = new ConcurrentHashMap<String, Set<NotifyListener>>();

    public void subscribe(String url, NotifyListener listener) {
        Set<NotifyListener> listeners = subscribed.get(url);
        if (listeners == null) {
            //不存在时放入
            subscribed.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
            listeners = subscribed.get(url);
        }
        listeners.add(listener);
    }

    public void notify(List<String> urls) {
        for (String url : urls) {
            for (Map.Entry<String, Set<NotifyListener>> entry : subscribed.entrySet()) {
                String _url = entry.getKey();
                if (!url.equals(_url)) {
                    continue;
                }
                Set<NotifyListener> listeners = entry.getValue();
                for (NotifyListener listener : listeners) {
                    listener.notify(url);
                }
            }
        }
    }
}
